import { getFriendsList, removeFriend } from "@/services/friend.js"
import { binMsg } from '@/global/api.js';
import router from '@/router/index.js'

const friendModule = {
  namespaced: true,
  state() {
    return {
      friendList: []
    }
  },

  mutations: {
    changefriendList(state, payload) {
      state.friendList = payload
    },
    // 更新好友最新消息和最新时间
    updateFriendList(state, payload) {
      state.friendList.forEach(item => {
        if (item.id === payload.id) {
          item.lastTime = payload?.time
          item.lastMsg = payload.content
        }
      })
    },
    // 前端更新未读消息+1
    updateUnreadCount(state, payload) {
      state.friendList.forEach(item => {
        if (item.id === payload.id) {
          item.unReadCount++
        }
      })
    },
    // 前端更改好友未读消息数量（进入哪个好友窗口，就直接设置对应好友的未读数量为0）
    updateMsgStateInFront(state, currentId) {
      // console.log(currentId)
      state.friendList.some(item => {
        if (item.id === currentId) {
          item.unReadCount = 0
          return true
        }
      })
    },
    // 前端移除好友
    removeFriendFromList(state, fid) {
      state.friendList = state.friendList.filter(item => item.id!==fid)
    }
  },

  actions: {
    // 获取好友列表
    async initFriendList({ commit }, payload) {
      const { data: { data: res } } = await getFriendsList(payload.id)
      commit('changefriendList', res.data)
    },
    // 移除好友
    async removef({ commit }, payload) {
      console.log(payload)
      // 后端移除
      const { data: res } = await removeFriend(payload.uid, payload.fid) 
      if (res.meta.status === 200) { 
        binMsg('success', res.meta.msg)
        // 前端移除
        commit('removeFriendFromList', payload.fid)
        // 跳转路由
        // const router = useRouter()
        router.replace('/home/message/chat')
      } else {
        return binMsg('danger', res.meta.msg)
      }

    }
  },

  getters: {
    // 搜索好友，关键词为空则返回全部
    searchFriend(state) {
      return function(keyword) {
        let newList = []
        state.friendList.forEach(item => {
          if (item.name.includes(keyword)) {
            newList.push(item)
          }
        })
        return newList
      }
    }
  }

}

export default friendModule
